import { useUserStoreHook } from '@/store/modules/user'

export const permission = {
  /**
   * Mounted hook for the permission directive.
   * This hook checks if the current user has the required roles to access the component.
   * If the user does not have the required roles, the component is removed from the DOM.
   *
   * @param {HTMLElement} el - The mounted element.
   * @param {Object} binding - The directive binding object.
   * @param {Array} binding.value - The required roles for the component.
   */
  mounted(el, binding) {
    const { value: permissionRoles } = binding
    const { roles } = useUserStoreHook()

    // Check if the permission roles are provided and are an array with at least one item
    if (Array.isArray(permissionRoles) && permissionRoles.length > 0) {
      // Check if the user has any of the required roles
      const hasPermission = roles.some(role => permissionRoles.includes(role))

      // If the user does not have any of the required roles, remove the component from the DOM
      if (!hasPermission) {
        el.parentNode?.removeChild(el)
      }
    } else {
      // If the permission roles are not provided or are an empty array, throw an error
      throw new Error(`need roles! "`)
    }
  },
}
